package com.gm.corejava.book2;

import sun.tools.jar.JarImageSource;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: camark@sina.cn
 * Date: 13-12-27
 * Time: 上午10:02
 */
public class ImageTransferFrame extends JFrame {

    private JLabel label;
    private Image image;

    public ImageTransferFrame(){
        setTitle("Image Transfer Test");
        setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);

        label=new JLabel();
        image=new BufferedImage(DEFAULT_WIDTH,DEFAULT_HEIGHT,BufferedImage.TYPE_INT_ARGB);
        Graphics g=image.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0,0,DEFAULT_WIDTH,DEFAULT_HEIGHT);
        g.setColor(Color.RED);
        g.fillOval(DEFAULT_WIDTH/4,DEFAULT_HEIGHT/4,DEFAULT_WIDTH/2,DEFAULT_HEIGHT/2);

        label.setIcon(new ImageIcon(image));
        add(new JScrollPane(label),BorderLayout.CENTER);

        JPanel btnPanel=new JPanel();

        JButton copyBtn=new JButton("Copy");
        copyBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Clipboard clipboard=Toolkit.getDefaultToolkit().getSystemClipboard();
                ImageTransferable imageTransferable=new ImageTransferable(image);
                clipboard.setContents(imageTransferable,null);
            }
        });
        btnPanel.add(copyBtn);

        JButton pasteBtn=new JButton("Paste");
        pasteBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Clipboard clipboard=Toolkit.getDefaultToolkit().getSystemClipboard();
                DataFlavor imageDataFlavor=DataFlavor.imageFlavor;

                if(clipboard.isDataFlavorAvailable(imageDataFlavor))
                {
                    Image tImage= null;
                    try {
                        tImage = (Image)clipboard.getData(DataFlavor.imageFlavor);
                    } catch (UnsupportedFlavorException e1) {
                        JOptionPane.showMessageDialog(ImageTransferFrame.this,e1);
                    } catch (IOException e1) {
                        JOptionPane.showMessageDialog(ImageTransferFrame.this,e1);
                    }
                    label.setIcon(new ImageIcon(tImage));
                }
            }
        });
        btnPanel.add(pasteBtn);

        add(btnPanel,BorderLayout.SOUTH);
    }
    private final int DEFAULT_WIDTH=400;
    private final int DEFAULT_HEIGHT=400;
}
